package com.uziot.bucket.web;

import com.alibaba.fastjson.JSONObject;
import com.uziot.bucket.task.CallBackTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @author shidt
 * @version V1.0
 * @className AsyncTestController
 * @date 2020-12-19 16:57:39
 * @description 控制器受理请求以及完成之后的回调任务
 */
@Slf4j
@RestController
public class AsyncTestController {

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    int i = 0;

    @GetMapping(value = "/user")
    public JSONObject getUserInfo() {
        log.info("查询用户信息开始...");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "张三");
        jsonObject.put("age", "20");
        log.info("查询用户信息完成...");
        // 执行异步回调任务
        threadPoolTaskExecutor.execute(new CallBackTask());
        return jsonObject;
    }

    @GetMapping("/callable/{loginId}")
    public Callable<Map<String, Object>> getResponse(@PathVariable String loginId) {
        Callable<Map<String, Object>> callable = () -> {
            Map<String, Object> result = new HashMap<>(1);
            result.put("loginId", loginId);
            if (i > 10) {
                result.put("当前值", i);
                result.put("结果", false);
                return result;
            } else {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        log.info("当前值I：" + i);
                        if (i >= 10) {
                            break;
                        } else {
                            i++;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                result.put("当前值", i);
                result.put("结果", true);
                return result;
            }
        };
        return callable;
    }
}
